﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ZealandIT.MsBuildTasks.Common
{
    public static class IoHelper
    {
        public static void AppendToFile(string file, string appendContent)
        {
            AppendToFileInternal(file, appendContent, null, null, null);
        }

        public static void AppendToFile(string file, string appendContent, string username, string password, string domain)
        {
            AppendToFileInternal(file, appendContent, username, password, domain);
        }

        private static void AppendToFileInternal(string file, string appendContent, string username, string password, string domain)
        {
            bool UseImpersonation = (username != null && password != null);
            if (UseImpersonation)
            {
                ImpersonationHelper imp = new ImpersonationHelper();
                if (imp.ImpersonateValidUser(username, domain, password))
                {
                    AppendContent(file, appendContent);
                    imp.UndoImpersonation();
                }
                else
                {
                    throw new Exception("Impersonation failed. File not appended to.");
                }
            }
            else
            {
                AppendContent(file, appendContent);
            }
        }

        private static void AppendContent(string file, string content)
        {
            using (StreamWriter sw = new StreamWriter(file, true))
            {
                sw.WriteLine();
                sw.WriteLine(content);
            }
        }

        /// <summary>
        /// Copies a directory and all its files and folders recursively to another directory.
        /// </summary>
        /// <param name="sourceFolder">Source dir</param>
        /// <param name="destFolder">Destination dir</param>
        public static void CopyDirectoryRecursively(string sourceFolder, string destFolder)
        {
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                File.Copy(file, Path.Combine(destFolder, name));
            }
            string[] folders = Directory.GetDirectories(sourceFolder);
            foreach (string folder in folders)
            {
                string name = Path.GetFileName(folder);
                Directory.CreateDirectory(Path.Combine(destFolder, name));
                CopyDirectoryRecursively(folder, Path.Combine(destFolder, name));
            }
        }

    }
}
